<template>
  <div>
    <a-card title="字符处理工具" :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form>
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-item label="类型">
                <a-select allowClear showSearch optionFilterProp="children"  @change="clear"
                          placeholder="类型" v-model:value="params.currentType" :options="types">
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-button type="default" @click="clear">重置</a-button>
            </a-col>
            <a-col :span="3" :offset="1">
            </a-col>
            <a-col :span="3">
            </a-col>
          </a-row>
        </a-form>
        <a-form class="str_transfer" v-if="params.currentType === 'specifications'" >
          <a-row :gutter="24">
            <a-col :span="7">
              <a-textarea v-model:value="params.inputData" @input="() => result = ''" placeholder="原始数据" :rows="10" />
            </a-col>
            <a-col :span="1" style="display: flex; align-items: center; justify-content: center;">
              <ArrowRightOutlined />
            </a-col>
            <a-col :span="10">
              <a-textarea v-model:value="result" placeholder="结果" :cols="8" maxCols="81" :rows="10" />
            </a-col>
            <a-col :span="2">
              <div style="margin-top: 20%">
                <a-row>
                  <a-select allowClear showSearch optionFilterProp="children"  style="width: 70%"
                            placeholder="分隔符" v-model:value="params.seperator" :options="seperators">
                  </a-select>
                </a-row>
                <a-row  style="margin-top: 6%">
                  <a-select allowClear showSearch optionFilterProp="children"   style="width: 70%"
                            placeholder="每行条数" v-model:value="params.chunkSize" :options="numbers2">
                  </a-select>
                </a-row>
                <a-row  style="margin-top: 10%;">
                  <a-button type="primary" @click="transferAction" >转 化</a-button>
                  <a-button type="default" class="specs" @click="() => copyToClipboard('specs')">复制</a-button>
                </a-row>
              </div>
            </a-col>
          </a-row>
        </a-form>
        <a-form class="str_cal" ref="formRef" :model="params" v-if="params.currentType === 'specsToVolume'" :rules="formRules">
          <a-row :gutter="24">
            <a-col :span="7">
              <a-form-item name="inputData">
                <a-textarea v-model:value="params.inputData" @input="() => result = ''"
                            placeholder="原始数据" :rows="10" />
              </a-form-item>
            </a-col>
            <a-col :span="1" style="display: flex; align-items: center; justify-content: center;">
              <ArrowRightOutlined />
            </a-col>
            <a-col :span="10">
              <a-textarea v-model:value="result" placeholder="结果" :cols="8" maxCols="81" :rows="10" />
            </a-col>
            <a-col :span="4">
              <div style="margin-top: 20%">
                <a-row>
                  <a-form-item name="isMergeSameSpecs">
                    <a-checkbox v-model:checked="params.isMergeSameSpecs"  >
                      是否相同规格合并
                    </a-checkbox>
                  </a-form-item>
                </a-row>
                <a-row style="margin-top: 6%">
                  <a-select allowClear showSearch optionFilterProp="children"  style="width: 70%"
                            placeholder="分隔符" v-model:value="params.seperator" :options="seperators">
                  </a-select>
                </a-row>
                <a-row  style="margin-top: 10%;">
                  <a-button type="primary" @click="calAction" >计算</a-button>
                  <a-button type="default" class="cal_volume" @click="() => copyToClipboard('cal_volume')">复制</a-button>
                </a-row>
              </div>
            </a-col>
          </a-row>
        </a-form>
        <a-form class="str_cal" v-if="params.currentType === 'removeSpecialStr'">
          <a-row :gutter="24">
            <a-col :span="7">
              <a-form-item>
                <a-textarea  v-model:value="params.inputData" @input="() => result = ''"
                             placeholder="原始数据" :rows="10" />
              </a-form-item>
            </a-col>
            <a-col :span="1" style="display: flex; align-items: center; justify-content: center;">
              <ArrowRightOutlined />
            </a-col>
            <a-col :span="10">
              <a-textarea v-model:value="result" placeholder="结果" :cols="8" maxCols="81" :rows="10" />
            </a-col>
            <a-col :span="4">
              <div style="margin-top: 20%">
                <a-row  style="margin-top: 10%;">
                  <a-button type="primary" @click="cleanAction">净化</a-button>
                </a-row>
              </div>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import {ref, computed, reactive} from 'vue';
import { postAction } from "@/utils/request.js";
import Clipboard from 'clipboard';
import { message } from 'ant-design-vue';


// 定义响应式数据
const formRef = ref(null);
const params = reactive({
  currentType: 'specifications',
  inputData: '',
  chunkSize: 0,
  seperator: ' ',
  isMergeSameSpecs: true
});
const result = ref('');
const cal_result = ref(0);
//// simple vars
const formRules =  {
  inputData: [
    { required: true, message: '请输入原始数据!' },
    { validator: handleSpecsCheck, validateTrigger: 'onBlur' }
  ],
  isMergeSameSpecs: []
}

const types = [
  { label: '货物规格字符处理', value: "specifications" },
  { label: '货物规格算体积', value: "specsToVolume" },
  { label: '特殊字符净化处理', value: "removeSpecialStr" },
]
const seperators = [
  { label: '回车符分隔', value: "\n" },
  { label: '空格分隔', value: " " },
]
const numbers = [
  { label: '0', value: 0 }, { label: '1', value: 1 }, { label: '2', value: 2 },
  { label: '3', value: 3 }, { label: '4', value: 4 }, { label: '5', value: 5 }, { label: '6', value: 6 }, { label: '7', value: 7 },
  { label: '8', value: 8 }, { label: '9', value: 9 }, { label: '10', value: 10 }, { label: '11', value: 11 }, { label: '12', value: 12 },
  { label: '13', value: 13 }, { label: '14', value: 14 }, { label: '15', value: 15 }, { label: '16', value: 16 }, { label: '17', value: 17 },
  { label: '18', value: 18 }, { label: '19', value: 19 }, { label: '20', value: 20 }, { label: '21', value: 21 }, { label: '22', value: 22 },
]
const SPECS_REGEX = /^[\s\n]*(([0-9]+\.?[0-9]*\*){2,3}[0-9]+\.?[0-9]*[\s\n])*([0-9]+\.?[0-9]*\*){2,3}[0-9]+\.?[0-9]*[\s\n]*$/;


// 计算属性
const url = computed(() => `/yg/stringHandler/${params.currentType}`);
const numbers2 = computed(() => {
  return numbers.map((item) => {
    return { label: item.value === 0 ? "不分行" : size_label(item.label), value: item.value };
  });
});

// 定义方法
function removeNonAlphanumericSpaces(str) {
  // 使用正则表达式匹配非字母、数字和空格字符，然后将其替换为空字符串
  return str.replace(/[^a-zA-Z0-9\s]/g,  ' ');
}

function handleSpecsCheck(rule, value) {
  const processedValue = value.replace(/[\s\n]+/g, " ");
  if (processedValue && !SPECS_REGEX.test(processedValue)) {
    return Promise.reject('规格数据不规范! 请检查格式！');
  } else {
    return Promise.resolve()
  }
}

const clear = () => {
  result.value = "";
  params.inputData = "";
};

const size_label = (n) => {
  return `每行${n}条`;
};

const transferAction = async () => {
  try {
    const res = await postAction(url.value, params);
    if (res && res.success) {
      result.value = res.data;
    }
  } catch (error) {
    console.error('转化操作出错', error);
  }
};

const cleanAction = () => {
  result.value = removeNonAlphanumericSpaces(params.inputData);
};

const calAction = () => {
  console.error("xxx")
  formRef.value
      .validate()
      .then(() => {
        postAction(url.value, params).then(res => {
          if (res && res.success) {
            result.value = res.data.process;
            cal_result.value = res.data.total;
          }
        });
      })
      .catch(error => {
        message.warning("表单信息验证失败");
        console.log('error', error);
      });
};

const copyToClipboard = (t) => {
  const res = t === "cal_volume" ? cal_result.value : result.value;
  const clipboard = new Clipboard("." + t, {
    text: () =>  res + ""
  });

  clipboard.on('success', () => {
    console.log('复制成功');
    clipboard.destroy();
    message.success('复制成功');
  });

  clipboard.on('error', () => {
    message.error('该浏览器不支持自动复制');
    clipboard.destroy();
  });
};

// 若 test 函数未使用，可移除
// const test = () => {
//   console.error("shit");
//   console.log("shit");
// };
</script>

<style scoped>
.container {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中，如果需要的话 */
  height: 100px; /* 容器的高度，根据实际情况设置 */
}
</style>
